#! /bin/sh

PROJECT_NAME=zbp-flowable-server
PROJECT_JAR=$PROJECT_NAME.jar

CURRENT_DIR=$(
    cd "$(dirname "$0")"
    pwd
)

# 进入部署目录
cd ${CURRENT_DIR}

# Function to check if a docker container is running
is_container_running() {
    container_name=$1
    if [ "$(docker ps -q -f name=^/${container_name}$)" ]; then
        return 0
    else
        return 1
    fi
}

# Step 1: Check PROJECT_JAR is exists
if [ ! -f "$PROJECT_JAR" ]; then
    echo "请先上传 '$PROJECT_JAR' 文件"
    exit 1
fi

# Step 2: Check for Docker
if ! command -v docker &> /dev/null; then
    echo "Docker is not installed. Please install Docker and try again."
    exit 1
fi

# Step 3: Check for Docker Compose
if ! command -v docker-compose &> /dev/null; then
    echo "Docker Compose is not installed. Please install Docker Compose and try again."
    exit 1
fi

# Step 4: Check if specified Docker container is running
if is_container_running $PROJECT_NAME; then
    docker stop $PROJECT_NAME && docker rm $PROJECT_NAME
    echo "'$PROJECT_NAME'容器已停止并移除"
else
    echo "Docker container '$PROJECT_NAME' is not running. Proceeding..."
fi

# Step 5: Build and starting the application using Docker Compose
echo "Build and starting the application with Docker Compose..."
docker-compose up --build -d

if [ $? -ne 0 ]; then
    echo "Failed to start the application with Docker Compose."
    exit 1
fi

# 清理空悬镜像
docker image prune -f

# Step 6: 备份并清理多余备份文件
echo "备份并清理多余备份文件"

TAG=$(date "+%Y%m%d%H%M")
mv ./$PROJECT_JAR ./bak/$PROJECT_JAR.$TAG

cd bak/
number=7
success=0
while (success=0)
do
del_file=`ls -l -crt $PROJECT_JAR.* | awk '{print $9 }' | head -1`
count=`ls -l -crt $PROJECT_JAR.* | awk '{print $9 }' | wc -l`
if [ $count -gt $number ]; then
   rm $del_file
   echo "删除最早生成的备份文件: $del_file"
else
   success=1
   break;
fi
done

echo "$PROJECT_NAME 安装完成"
echo "通过日志查看启动结果"
docker-compose logs -f --tail 100 